package com.CmJava.handler;

import com.CmJava.service.JwtService;
import com.CmJava.utils.TokenManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.logout.LogoutHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ChatLogoutHandler implements LogoutHandler {

    private JwtService jwtService;

    public ChatLogoutHandler(JwtService jwtService) {
        this.jwtService=jwtService;
    }

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        String userName = ((User) authentication.getPrincipal()).getUsername();
        String remoteAddr = request.getRemoteAddr();
        String token = jwtService.getJwt(userName);
        String userIp = TokenManager.getUserIp(token);

        if (userIp.equals(remoteAddr)){
            jwtService.logout(userName);
        }
    }

}
